package com.quan.bookmall.controller;

import com.quan.bookmall.dto.OrderDTO;
import com.quan.bookmall.dto.request.OrderQueryRequest;
import com.quan.bookmall.dto.response.ApiResponse;
import com.quan.bookmall.dto.response.StatisticsResponse;
import com.quan.bookmall.security.UserDetailsImpl;
import com.quan.bookmall.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
public class OrderController {
    
    private final OrderService orderService;
    
    @GetMapping
    public ResponseEntity<?> getOrders(
            @AuthenticationPrincipal UserDetailsImpl userDetails,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createTime").descending());
        Page<OrderDTO> orders = orderService.findByUserId(userDetails.getId(), pageable);
        return ResponseEntity.ok(ApiResponse.success(orders));
    }
    
    @GetMapping("/search")
    public ResponseEntity<?> searchOrders(
            @AuthenticationPrincipal UserDetailsImpl userDetails,
            OrderQueryRequest queryRequest) {
        
        Page<OrderDTO> orders = orderService.findByUserIdAndConditions(userDetails.getId(), queryRequest);
        return ResponseEntity.ok(ApiResponse.success(orders));
    }
    
    @GetMapping("/all")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> getAllOrders(OrderQueryRequest queryRequest) {
        Page<OrderDTO> orders = orderService.findByConditions(queryRequest);
        return ResponseEntity.ok(ApiResponse.success(orders));
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<?> getOrderById(
            @AuthenticationPrincipal UserDetailsImpl userDetails,
            @PathVariable Long id) {
        
        OrderDTO orderDTO = orderService.findById(id);
        
        // 非管理员只能查看自己的订单
        if (!userDetails.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))
                && !orderDTO.getUserId().equals(userDetails.getId())) {
            return ResponseEntity.status(403).body(ApiResponse.error("无权访问此订单"));
        }
        
        return ResponseEntity.ok(ApiResponse.success(orderDTO));
    }
    
    @PostMapping
    public ResponseEntity<?> createOrder(@AuthenticationPrincipal UserDetailsImpl userDetails) {
        OrderDTO orderDTO = orderService.createFromCart(userDetails.getId());
        return ResponseEntity.ok(ApiResponse.success(orderDTO));
    }
    
    @GetMapping("/statistics/book-sales")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> getBookSalesStatistics(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        StatisticsResponse response = orderService.getBookSalesStatistics(startTime, endTime);
        return ResponseEntity.ok(ApiResponse.success(response));
    }
    
    @GetMapping("/statistics/user-consumption")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> getUserConsumptionStatistics(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        StatisticsResponse response = orderService.getUserConsumptionStatistics(startTime, endTime);
        return ResponseEntity.ok(ApiResponse.success(response));
    }
    
    @GetMapping("/statistics/my-books")
    public ResponseEntity<?> getMyBookStatistics(
            @AuthenticationPrincipal UserDetailsImpl userDetails,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        StatisticsResponse response = orderService.getUserBookStatistics(userDetails.getId(), startTime, endTime);
        return ResponseEntity.ok(ApiResponse.success(response));
    }
} 